home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
PC World Komputer 2010 April
/
PCWorld0410.iso
/
pluginy Firefox
/
11587
/
11587.xpi
/
chrome
/
aviary.jar
/
content
/
browserOverlay.js
< prev
next >
Wrap
Text File
|
2009-10-16
|
40KB
|
1,183 lines
/* Copyright (c) 2007-2009 Pearl Crescent, LLC. All Rights Reserved. */
/* vim: set sw=2 sts=2 ts=8 et syntax=javascript: */
var gAviaryMain =
{
kExtensionID: "{d5eeb813-935a-435d-b01e-b3a02f2cb408}",
kLoginURLSuffix: "/login",
kLaunchAppURLSuffix: "/flash/aviary/index.aspx",
kLaunchFalconURLSuffix: "/launch/falcon",
kWelcomeURISuffix: "/tools/talon",
kNewVersionURISuffix: "/tools/talon?v=",
kToolbarItemID : "aviary-captureimageofpage",
kStatusbarItemID : "aviary-statusbar-capture",
kStatusbarID: "status-bar",
kNavBarID: "nav-bar",
kTBInitialInstallPref : "aviary.toolbar.initialinstallation",
kWarnIfNotLoggedInPref : "aviary.warnIfNotLoggedIn",
kTBItemLocationPref : "aviary.toolbarItem.location",
kLastVersionPref : "aviary.lastVersion",
// These constants are also in options.xul
kPortionRegion: 0,
kPortionVisible: 1,
kPortionEntire: 2,
// These constants are also in actionPrompt.xul
kActionNone: 0,
kActionSaveToAviary: 1,
kActionSaveAndOpen: 2,
kActionSaveToDesktop: 3,
kActionCopyToClipboard: 4,
kActionPrompt: 5,
mAuthService: null,
mConnectService: null,
mPearlUtil: null,
mPreviousSearchEngine: null,
LoginOrOut: function()
{
var isLoggedIn = false;
if (this.mAuthService)
isLoggedIn = this.mAuthService.isLoggedIn;
if (isLoggedIn)
this.mAuthService.Logout();
else
this.OpenInNewTab(this.getLoginURL(), null);
},
setLoginState: function(aIsLoggedIn)
{
var loginButton = document.getElementById("aviary-login");
var labelAttr = aIsLoggedIn ? "aviaryLogoutLabel" : "aviaryLoginLabel";
if (loginButton)
{
var s = loginButton.getAttribute(labelAttr);
loginButton.setAttribute("label", s);
if (aIsLoggedIn)
loginButton.setAttribute("aviaryloggedin", aIsLoggedIn);
else
loginButton.removeAttribute("aviaryloggedin");
}
this.mPearlUtil.SetElementAttribute("aviary-dashboard", "hidden",
!aIsLoggedIn);
this.mPearlUtil.SetElementAttribute("aviary-settings", "hidden",
!aIsLoggedIn);
},
setToolsList: function(aToolList)
{
if (!aToolList && this.mAuthService)
aToolList = this.mAuthService.toolsList;
// Only show top-level menu items for active tools.
gAviaryUtil.HideInactiveTools(aToolList);
},
getLoginURL: function()
{
return this.mPearlUtil.GetASCIIPref("aviary.serverPrefix", "")
+ this.kLoginURLSuffix;
},
LaunchAppByToolID: function(aToolID, aFileGUID, aImageURL, aImageInfo)
{
var serverPrefix = this.mPearlUtil.GetASCIIPref("aviary.serverPrefix", "");
if (!serverPrefix)
return;
var urlParamInfo = {
1: { urlParams: "tid=1&Phoenix" },
2: { urlParams: "tid=2&Toucan" },
3: { urlParams: "tid=3&Peacock" },
4: { urlParams: "tid=4&Raven" },
5: { urlParams: "tid=5&Hummingbird" },
6: { urlParams: "tid=6&Myna" },
14: { urlParams: "tid=14&Woodpecker" }};
var url = serverPrefix;
var infoObj = urlParamInfo[aToolID];
if (!infoObj)
url += this.kLaunchFalconURLSuffix; // Launch Falcon (tid=20) by default.
else
{
url += this.kLaunchAppURLSuffix;
url = this.appendURLParam(url, infoObj.urlParams);
}
if (aFileGUID)
url = this.appendURLParam(url, "fguid=" + encodeURIComponent(aFileGUID));
if (aImageURL)
url = this.appendURLParam(url, "url=" + encodeURIComponent(aImageURL));
if (aImageInfo)
{
if (aImageInfo.id)
url = this.appendURLParam(url, "imageid=" + aImageInfo.id);
if (aImageInfo.width && aImageInfo.height)
{
url = this.appendURLParam(url, "width=" + aImageInfo.width);
url = this.appendURLParam(url, "height=" + aImageInfo.height);
}
}
var params = "fullscreen=yes,resizable=yes,menubar=no,location=no,status=no,toolbar=no";
// TODO: use GUID for window name when appropriate; bring to front, etc.
var win = window.open(url, 'x', params);
},
appendURLParam: function(aURL, aEncodedParam)
{
if (!aURL || !aEncodedParam)
return aURL;
aURL += (aURL.indexOf('?') < 0) ? '?' : '&';
return aURL + aEncodedParam;
},
LaunchApp: function(aTBItem)
{
if (!aTBItem)
return;
var toolID = aTBItem.getAttribute("aviary-tid");
this.LaunchAppByToolID(toolID, null, null, null);
},
OpenURLFromMenu: function(aMenuItem, aEvent)
{
if (!aMenuItem)
return;
this.OpenURL(aMenuItem.getAttribute("url"), aEvent, true);
},
OpenTalonOptions: function()
{
this.mPearlUtil.OpenPrefsWindow("aviary:prefs",
"chrome://aviary/content/options.xul");
},
CaptureDefault: function()
{
var pagePortion = this.mPearlUtil.GetIntPref("aviary.defaultCaptureType",
this.kPortionRegion);
if (this.kPortionRegion == pagePortion)
this.CaptureRegion();
else
this.CaptureImageOfPage(pagePortion, this.kActionPrompt);
},
CaptureRegion: function()
{
var isLoggedIn = this.mAuthService.isLoggedIn;
if (!isLoggedIn && this.promptToLogin(true))
return;
var win = this.mPearlUtil.GetTopBrowserWindow();
var r = {};
r.startX = win.pageXOffset;
r.startY = win.pageYOffset;
r.pageW = this.mPearlUtil.GetWindowWidth(win, false);
r.pageH = this.mPearlUtil.GetWindowHeight(win, false);
var reminderElem = document.getElementById("AviaryDragReminder");
if (reminderElem)
{
if (r.pageW > 80)
reminderElem.style.maxWidth = (r.pageW - 40) + "px";
else
reminderElem.style.maxWidth = r.pageW + "px";
reminderElem.style.display = "block";
if (r.pageH > 120 && r.pageW > 300) // heuristic
reminderElem.style.marginTop = "40px";
else
reminderElem.style.marginTop = "0px";
var popupElem = document.getElementById("AviarySelectionPopup");
if (popupElem)
{
var mouseDownListener = function(aEvent)
{
reminderElem.style.display = "none";
popupElem.removeEventListener("mousedown", mouseDownListener, true);
};
popupElem.addEventListener("mousedown", mouseDownListener, true);
}
}
com.aviary.talon.grab.init(win, r, null, 0, true,
this.RegionCaptureCallback, null);
},
// aAction is ignored if aPagePortion == gAviaryMain.kPortionRegion.
// Otherwise, aAction should be one of the gAviaryMain.kAction constants.
CaptureImageOfPage: function(aPagePortion, aAction)
{
if (this.kPortionRegion != aPagePortion && !this.mAuthService.isLoggedIn)
{
var actionIsSave = (this.kActionSaveToAviary == aAction);
if (actionIsSave || this.kActionPrompt == aAction)
{
var didOpenLoginPage = this.promptToLogin(!actionIsSave);
if (actionIsSave || didOpenLoginPage)
return;
}
}
var win = this.mPearlUtil.GetTopBrowserWindow();
this.captureAndUploadImage(win, null, aPagePortion, null, aAction);
},
RegionCaptureCallback: function(aBrowserWin, aRegionRect, aArg, aDoCancel)
{
if (aBrowserWin && aRegionRect && !aDoCancel)
{
gAviaryMain.captureAndUploadImage(aBrowserWin, null,
gAviaryMain.kPortionRegion,
aRegionRect, gAviaryMain.kActionPrompt);
}
},
// If aImageNode is null, the background image is used.
EditImage: function(aImageNode)
{
// aImageNode.src and bgImageURL are always fully qualified URLs.
var imgURL = (aImageNode) ? aImageNode.src : gContextMenu.bgImageURL;
if (!imgURL)
{
if (aImageNode) // Must be a canvas; so try to upload and then edit it.
this.SaveImage(aImageNode, true);
return;
}
var tid = this.mPearlUtil.GetIntPref("aviary.defaultImageEditor", 20);
if (20 == tid) // Falcon
{
this.LaunchAppByToolID(tid, null, imgURL, null);
return;
}
try
{
gAviaryUpload.UploadByURL(imgURL, tid);
}
catch (e) { dump(e + "\n"); } // TODO: improve error reporting.
},
SaveImage: function(aImageNode, aDoUploadAndEdit)
{
if (!aImageNode)
return;
if (!this.mAuthService.isLoggedIn)
{
this.promptToLogin(false);
return;
}
var win = this.mPearlUtil.GetTopBrowserWindow();
var action = (aDoUploadAndEdit) ? this.kActionSaveAndOpen
: this.kActionSaveToAviary;
this.captureAndUploadImage(win, aImageNode, 0, null, action);
},
SaveBGImage: function()
{
if (!this.mAuthService.isLoggedIn)
{
this.promptToLogin(false);
return;
}
if (gContextMenu.bgImageURL) try
{
gAviaryUpload.UploadByURL(gContextMenu.bgImageURL, 0);
}
catch (e) { dump(e + "\n"); } // TODO: improve error reporting.
},
// If aImageElement is null, the active page is captured.
// aPagePortion and aRegionRect affect active page captures.
captureAndUploadImage: function(aWin, aImageElement, aPagePortion,
aRegionRect, aAction)
{
if (this.kPortionRegion == aPagePortion && !aRegionRect)
aPagePortion = this.kPortionVisible;
var progressMeter = new AviaryProgressMeter();
if (progressMeter)
{
progressMeter.SetIsCancelable(true);
var str = this.mPearlUtil.GetLocalizedString("CAPTURING_IMAGE");
progressMeter.SetLabel(str);
}
// Use setTimeout() here so progress meter is rendered before we
// get inside slow functions like canvas.drawWindow().
var self = this;
window.setTimeout(function() { self.captureAndUploadImage2(aWin, aImageElement, aPagePortion, aRegionRect, aAction, progressMeter) }, 0);
},
captureAndUploadImage2: function(aWin, aImageElement, aPagePortion,
aRegionRect, aAction, aProgressMeter)
{
if (aAction == this.kActionPrompt)
{
// Display modal dialog to prompt for action.
var dlogflags = "chrome,titlebar,centerscreen,modal";
var paramObj = new Object();
paramObj.action = this.kActionNone;
paramObj.authService = this.mAuthService;
paramObj.loginURL = this.getLoginURL();
window.openDialog("chrome://aviary/content/actionPrompt.xul", "_blank",
dlogflags, paramObj);
aAction = paramObj.action;
}
if (aAction == this.kActionPrompt || aAction == this.kActionNone)
{
if (aProgressMeter)
aProgressMeter.Close(false, null);
return;
}
// Attempt to get a file name from the image element or page title.
// Also, get originating URL (page URL or image URL) for image captures.
var fname;
var origURL;
if (this.kActionCopyToClipboard != aAction) try
{
// TODO: don't set fname if copying to clipboard.
if (this.kActionSaveToDesktop == aAction)
{
// Set fname to the page's domain if we are saving to the desktop.
if (aWin && aWin.document && aWin.document.location)
{
fname = aWin.document.location.hostname;
if (fname)
{
fname = fname.replace(/^www\./, '');
fname = fname.replace(/\./g, '-');
}
}
}
else if (aImageElement)
{
var ioService = Components.classes["@mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
var imageURI = ioService.newURI(aImageElement.src, null, null);
var imageURL = imageURI.QueryInterface(Components.interfaces.nsIURL);
origURL = imageURL.spec;
fname = imageURL.fileName;
if (fname)
{
var dotIndex = fname.lastIndexOf('.');
if (dotIndex >= 0)
fname = fname.substring(0, dotIndex);
fname += ".png";
}
}
else if (aWin && aWin.document)
{
origURL = aWin.document.location;
var docTitle = aWin.document.title;
if (docTitle)
docTitle = docTitle.replace(/[^\x20-\x7E]/g, ''); // Remove non-ASCII
fname = this.mPearlUtil.SanitizeFileName(docTitle) + ".png";
}
// else fname = null;
} catch (e) {}
try
{
var cpiObj = new AviaryCapturePageImage(aWin, aImageElement,
aPagePortion, aRegionRect);
var sizeObj = new Object;
cpiObj.DrawImageOnCanvas(sizeObj);
var dataURI;
if (!aProgressMeter || !aProgressMeter.IsCanceled())
dataURI = cpiObj.GetPNGDataURI();
cpiObj.Cleanup();
if (aProgressMeter && aProgressMeter.IsCanceled())
{
aProgressMeter.Close(false, null);
return;
}
// Use setTimeout() here so user has a chance to cancel.
var self = this;
window.setTimeout(
function()
{
self.captureAndUploadImage3(dataURI, sizeObj, fname, origURL,
aAction, aProgressMeter);
}, 0);
} catch (e) { dump(e + "\n"); } // TODO: improve error reporting.
// TODO: cleanup progress meter on error
},
// Note: aName may be null.
captureAndUploadImage3: function(aDataURI, aSizeObj, aName, aOriginatingURL,
aAction, aProgressMeter)
{
try
{
if (this.mPearlUtil.GetBoolPref("aviary.showCapturedImageInTab", false))
{
this.OpenInNewTab(aDataURI, null);
if (aProgressMeter)
aProgressMeter.Close(false, null);
return;
}
if (aProgressMeter && aProgressMeter.IsCanceled())
{
aProgressMeter.Close(false, null);
return;
}
if (this.kActionCopyToClipboard == aAction)
{
if (aProgressMeter)
aProgressMeter.SetIsCancelable(false); // too late to cancel now.
var self = this;
var cbFunc = function(aDidSucceed)
{
self.ClipboardCopyCompleteCallback(aProgressMeter, aDidSucceed);
};
com.aviary.talon.clipboard.CopyDataURIToClipboard(aDataURI, cbFunc);
return;
}
var tid = this.mPearlUtil.GetIntPref("aviary.defaultImageEditor", 20); // Falcon
if ((20 == tid) && this.mConnectService
&& (this.kActionSaveAndOpen == aAction))
{
// Register captured image with component to be pulled out later
// by Flash application.
var imageInfoObj = new Object;
imageInfoObj.id = this.mConnectService.addCapturedImage("image/png",
aDataURI);
if (aSizeObj)
{
imageInfoObj.width = aSizeObj.width;
imageInfoObj.height = aSizeObj.height;
}
this.LaunchAppByToolID(tid, null, null, imageInfoObj);
if (aProgressMeter)
aProgressMeter.Close(false, null);
return;
}
var ioService = Components.classes["@mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
var uriObj = ioService.newURI(aDataURI, null, null);
var dataChannel = ioService.newChannelFromURI(uriObj);
var binStream = Components.classes["@mozilla.org/binaryinputstream;1"]
.createInstance(Components.interfaces.nsIBinaryInputStream);
binStream.setInputStream(dataChannel.open());
// Use setTimeout() here so user has a chance to cancel.
var self = this;
window.setTimeout(function() { self.captureAndUploadImage4(binStream, aName, aOriginatingURL, aAction, aProgressMeter); }, 150);
}
catch (e) { dump(e + "\n"); } // TODO: improve error reporting.
// TODO: clean up progress meter on error?
},
// Note: this function is not used when copying to the clipboard.
captureAndUploadImage4: function(aImageStream, aName, aOriginatingURL,
aAction, aProgressMeter)
{
if (this.kActionSaveToDesktop == aAction)
{
this.promptAndSaveToFile(aImageStream, aName, aProgressMeter);
}
else try
{
var tid = 0;
if (this.kActionSaveAndOpen == aAction)
tid = this.mPearlUtil.GetIntPref("aviary.defaultImageEditor", 20); // Falcon
gAviaryUpload.UploadStream("image/png", aImageStream, aName,
aOriginatingURL, aProgressMeter, tid);
}
catch (e) { dump(e + "\n"); } // TODO: improve error reporting.
// TODO: clean up progress meter on error?
},
ClipboardCopyCompleteCallback: function(aProgressMeter, aDidSucceed)
{
if (aDidSucceed)
{
if (aProgressMeter)
{
aProgressMeter.SetValue(100);
aProgressMeter.Close(true, "IMAGE_COPIED"); // fade out
}
}
else
{
if (aProgressMeter)
aProgressMeter.Close(false, null);
var s = this.mPearlUtil.GetLocalizedString("ERROR_UNABLE_TO_COPY")
this.mPearlUtil.Alert(window, s);
}
},
observe: function(aSubject, aTopic, aData)
{
if ("aviary:loginstatus" == aTopic)
this.setLoginState("true" == aData);
else if ("aviary:toolsavailable" == aTopic)
this.setToolsList(aData);
else if ("browser-search-engine-modified" == aTopic
&& "engine-current" == aData)
{
var obsSvc = Components.classes["@mozilla.org/observer-service;1"]
.getService(Components.interfaces.nsIObserverService);
obsSvc.removeObserver(this, aTopic);
if (this.mPreviousSearchEngine)
{
var searchSvc =
Components.classes["@mozilla.org/browser/search-service;1"]
.getService(Components.interfaces.nsIBrowserSearchService);
searchSvc.currentEngine = this.mPreviousSearchEngine;
this.mPreviousSearchEngine = null;
}
}
else if ("nsPref:changed" == aTopic)
{
if (this.kTBItemLocationPref == aData)
{
var newLoc = this.mPearlUtil.GetASCIIPref(this.kTBItemLocationPref);
var onStatusbar = (this.kStatusbarID == newLoc);
this.showToolbarItem(onStatusbar ? null : newLoc);
this.showStatusbarItem(onStatusbar);
}
}
},
// Pass null for aToolbarID to remove item.
showToolbarItem: function(aToolbarID)
{
if (!aToolbarID)
{
this.removeToolbarItem();
return;
}
var item = document.getElementById(this.kToolbarItemID);
if (item)
{
if (item.parentNode.id == aToolbarID)
return; // Already on correct toolbar.
this.removeToolbarItem(); // On wrong toolbar. Remove it.
}
var toolbar = document.getElementById(aToolbarID);
if (!toolbar)
{
aToolbarID = this.kNavBarID;
toolbar = document.getElementById(aToolbarID);
if (!toolbar)
return; // Tried to fallback to navbar and failed. Give up.
}
var afterID = null;
if (this.kNavBarID == aToolbarID)
{
// On navbar, place "capture image" toolbar item after the home button.
var homeBtn = document.getElementById("home-button");
if (homeBtn && (homeBtn.parentNode == toolbar) && homeBtn.nextSibling)
afterID = homeBtn.nextSibling.id;
}
this.prepareToCustomizeToolbox();
this.mPearlUtil.ShowToolbarItem(document, this.kToolbarItemID, afterID,
aToolbarID);
this.customizeToolboxDone();
},
removeToolbarItem: function()
{
var item = document.getElementById(this.kToolbarItemID);
if (item)
{
var toolbar = item.parentNode;
var itemArray = toolbar.currentSet.split(',');
var itemFound = false;
for (var i = 0; !itemFound && (i < itemArray.length); ++i)
{
if (itemArray[i] == this.kToolbarItemID)
{
itemFound = true;
itemArray.splice(i, 1); // remove from array
}
}
if (itemFound)
{
this.prepareToCustomizeToolbox();
var cs = itemArray.join(',');
toolbar.setAttribute("currentset", cs);
toolbar.currentSet = cs;
document.persist(toolbar.id, "currentset");
this.customizeToolboxDone();
}
}
},
prepareToCustomizeToolbox: function()
{
var splitter = document.getElementById("urlbar-search-splitter");
if (splitter)
splitter.parentNode.removeChild(splitter);
},
// Re-init toolbars after a change was made, e.g., toolbar item added.
customizeToolboxDone: function()
{
try
{
BrowserToolboxCustomizeDone(true);
}
catch (e) {}
},
showStatusbarItem: function(aDoShow)
{
this.mPearlUtil
.SetElementAttribute(this.kStatusbarItemID, "hidden", !aDoShow);
},
OpenInNewTab: function(aURL, aEvent)
{
this.OpenURL(aURL, aEvent, true);
},
OpenURL: function(aURL, aEvent, aInNewTab)
{
if (aURL)
{
var winToUse;
try
{
// If this is a popup window, find a non-popup one to use.
if (window.document.documentElement.getAttribute("chromehidden"))
{
const kWMClass = "@mozilla.org/appshell/window-mediator;1";
var wmSvc = Components.classes[kWMClass]
.getService(Components.interfaces.nsIWindowMediator);
var winEnum = wmSvc.getZOrderDOMWindowEnumerator("navigator:browser",
true);
while (!winToUse && winEnum.hasMoreElements())
{
var w = winEnum.getNext();
var chromeHidden = w.document.documentElement
.getAttribute("chromehidden");
if (!chromeHidden && w != window)
winToUse = w;
}
}
} catch (e) {}
if (!winToUse)
winToUse = window;
var tabBrowser = winToUse.top.getBrowser();
if (aInNewTab)
{
var newtab = winToUse.openNewTabWith(aURL, null, null, aEvent, false);
if (tabBrowser && newtab)
tabBrowser.selectedTab = newtab;
}
else if (tabBrowser)
tabBrowser.loadURI(aURL);
}
},
onLoad: function()
{
this.mPearlUtil = com.aviary.talon.pearlutil;
// Add hook so we can update the context menu when it is invoked.
var menu = document.getElementById("contentAreaContextMenu");
if (menu)
{
menu.addEventListener("popupshowing",
this.onContextMenuShowing, false);
}
// Remove outdated preference.
this.mPearlUtil.ClearUserPref("aviary.defaultEditor");
// Add observers and initialize login state.
try
{
var obsSvc = Components.classes["@mozilla.org/observer-service;1"]
.getService(Components.interfaces.nsIObserverService);
obsSvc.addObserver(this, "aviary:loginstatus", false);
obsSvc.addObserver(this, "aviary:toolsavailable", false);
var prefSvc = this.mPearlUtil.mPrefService;
prefSvc.addObserver(this.kTBItemLocationPref, this, false);
const kAuthServiceCID = "@aviary.com/aviary-auth;1";
this.mAuthService = Components.classes[kAuthServiceCID]
.getService(Components.interfaces.aviaryIAuth);
this.setLoginState(this.mAuthService.isLoggedIn);
this.setToolsList(null);
const kConnectServiceCID = "@aviary.com/aviary-api;1";
this.mConnectService = Components.classes[kConnectServiceCID]
.getService(Components.interfaces.aviaryIConnectInternal);
}
catch(e) {}
// Show status bar item if pref says to do so.
var itemLoc = this.mPearlUtil.GetASCIIPref(this.kTBItemLocationPref);
this.showStatusbarItem(this.kStatusbarID == itemLoc);
var self = this;
window.setTimeout(function() { self.DelayedInit(itemLoc); }, 0);
}, // onLoad()
DelayedInit: function(aItemLocation)
{
// If first time we have been loaded, add toolbar items, etc.
var isFirstTime = this.mPearlUtil
.GetBoolPref(this.kTBInitialInstallPref, true);
if (isFirstTime)
{
this.mPearlUtil.SetBoolPref(this.kTBInitialInstallPref, false);
this.OnFirstLoad(aItemLocation);
}
// Display "Welcome" or "Upgrade" page in a new tab if appropriate:
var extVer;
try
{
var extMgr = Components.classes["@mozilla.org/extensions/manager;1"]
.getService(Components.interfaces.nsIExtensionManager);
var extInfo = extMgr.getItemForID(this.kExtensionID);
extVer = extInfo.version;
} catch (e) {}
var uriSuffix;
var lastVer = this.mPearlUtil.GetLocalizedStrPref(this.kLastVersionPref);
if (!lastVer && !isFirstTime)
lastVer = "0.8.7.1"; // or earlier, but close enough.
if (!lastVer)
uriSuffix = this.kWelcomeURISuffix;
else if (extVer && lastVer != extVer)
uriSuffix = this.kNewVersionURISuffix + extVer;
if (uriSuffix)
{
var failedToWritePrefs = false;
if (extVer)
{
this.mPearlUtil.SetLocalizedStrPref(this.kLastVersionPref, extVer);
try
{
// Flush preferences file. If it fails, do not open our page.
var prefS = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefService);
prefS.savePrefFile(null);
}
catch(e)
{
failedToWritePrefs = true;
}
}
if (!failedToWritePrefs)
{
var tabBrowser = top.getBrowser();
var serverPrefix = this.mPearlUtil.GetASCIIPref("aviary.serverPrefix");
if (tabBrowser && serverPrefix)
{
tabBrowser.loadOneTab(serverPrefix + uriSuffix, null, null, null,
false, false);
}
}
}
}, // DelayedInit()
OnFirstLoad: function(aItemLocation)
{
if (aItemLocation && (this.kStatusbarID != aItemLocation))
this.showToolbarItem(aItemLocation);
// Add Aviary search engine.
// TODO: do not add if already present, e.g., added via website.
try
{
var emSvc = Components.classes["@mozilla.org/extensions/manager;1"]
.getService(Components.interfaces.nsIExtensionManager);
var fileLoc = emSvc.getInstallLocation(this.kExtensionID)
.getItemLocation(this.kExtensionID);
fileLoc.append("defaults");
fileLoc.append("search.xml");
var ioSvc = Components.classes["@mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
var fileURI = ioSvc.newFileURI(fileLoc);
var searchSvc =
Components.classes["@mozilla.org/browser/search-service;1"]
.getService(Components.interfaces.nsIBrowserSearchService);
this.mPreviousSearchEngine = searchSvc.currentEngine;
if (this.mPreviousSearchEngine)
{
var obsSvc = Components.classes["@mozilla.org/observer-service;1"]
.getService(Components.interfaces.nsIObserverService);
obsSvc.addObserver(this, "browser-search-engine-modified", false);
}
// NOTE: if the engine is already installed, this call has no effect.
// Also, addEngine() makes a copy of the xml file so to update we'll
// need to removeEngine() and then addEngine() again.
searchSvc.addEngine(fileURI.spec,
Components.interfaces.nsISearchEngine.DATA_XML,
null, false);
}
catch (e) {}
}, // OnFirstLoad()
onContextMenuShowing: function()
{
if (gContextMenu)
{
var viewmenuitem = document.getElementById("context-viewimage");
var copymenuitem = document.getElementById("context-copyimage");
const kCI = Components.interfaces;
var isAnImage = ((viewmenuitem && !viewmenuitem.hidden) ||
(copymenuitem && !copymenuitem.hidden)) &&
((document.popupNode instanceof kCI.nsIDOMHTMLImageElement) ||
(document.popupNode instanceof kCI.nsIDOMHTMLCanvasElement));
gContextMenu.showItem("aviary-editImage", isAnImage);
gContextMenu.showItem("aviary-editBGImage",
!isAnImage && gContextMenu.hasBGImage);
gContextMenu.showItem("aviary-saveBGImage",
!isAnImage && gContextMenu.hasBGImage);
gContextMenu.showItem("aviary-saveImage", isAnImage);
gContextMenu.showItem("aviary-editThisImage", isAnImage);
gContextMenu.showItem("aviary-editThisBGImage",
!isAnImage && gContextMenu.hasBGImage);
}
},
// returns true if login page was opened.
promptToLogin: function(aCanContinue)
{
if (aCanContinue &&
!this.mPearlUtil.GetBoolPref(this.kWarnIfNotLoggedInPref, true))
{
return false;
}
const knsIPS = Components.interfaces.nsIPromptService;
var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
.getService(knsIPS);
var title = this.mPearlUtil.GetLocalizedString("ALERT_TITLE");
var token = (aCanContinue) ? "NOT_LOGGED_IN_CONTINUE" : "NOT_LOGGED_IN";
var msg = this.mPearlUtil.GetLocalizedString(token);
var btn0Label = this.mPearlUtil.GetLocalizedString("LOGIN_BUTTON_LABEL");
var btn1Label = null;
var cbLabel = null;
var flags = knsIPS.BUTTON_POS_0 * knsIPS.BUTTON_TITLE_IS_STRING
+ knsIPS.BUTTON_POS_0_DEFAULT;
if (aCanContinue)
{
flags += knsIPS.BUTTON_POS_1 * knsIPS.BUTTON_TITLE_IS_STRING;
btn1Label = this.mPearlUtil.GetLocalizedString("CONTINUE_BUTTON_LABEL");
cbLabel = this.mPearlUtil.GetLocalizedString("CONTINUE_CHECKBOX_LABEL");
}
else
flags += knsIPS.BUTTON_POS_1 * knsIPS.BUTTON_TITLE_CANCEL;
var checkState = { value: false };
var rv = ps.confirmEx(window, title, msg, flags, btn0Label,
btn1Label, null, cbLabel, checkState);
var doLogin = (0 == rv);
if (doLogin)
this.OpenInNewTab(this.getLoginURL(), null);
if (checkState.value)
this.mPearlUtil.SetBoolPref(this.kWarnIfNotLoggedInPref, false);
return doLogin;
},
promptAndSaveToFile: function(aImageStream, aDomainName, aProgressMeter)
{
const kFileExt = ".png";
var baseName;
if (aDomainName)
{
baseName = this.mPearlUtil.GetFormattedLocalizedString(
"FILE_BASENAME_WITH_URL", [aDomainName], 1);
baseName = this.mPearlUtil.SanitizeFileName(baseName);
}
else
baseName = this.mPearlUtil.GetLocalizedString("FILE_BASENAME");
var defaultLoc = this.mPearlUtil.GetFileLocation("Desk", baseName,
kFileExt);
var prompt = this.mPearlUtil.GetLocalizedString("FILE_SAVE_PROMPT");
var filterName = this.mPearlUtil.GetLocalizedString("FILE_FILTERNAME")
var fileLoc = this.mPearlUtil.FilePickerSaveAs(prompt, filterName,
kFileExt, defaultLoc);
var resultCode = 0;
if (fileLoc) // User chose a file (did not cancel).
resultCode = this.mPearlUtil.WriteStreamToFile(aImageStream, fileLoc);
if (aProgressMeter)
aProgressMeter.Close(false, null);
if (0 != resultCode)
{
var strName = "writeError";
const kFileErrorBase = 0x80520000;
switch (resultCode - kFileErrorBase)
{
/* We do not expect this error, and Mozilla's error message is odd.
case 8: // NS_ERROR_FILE_ALREADY_EXISTS
strName = "fileAlreadyExistsError";
break;
*/
case 10: // NS_ERROR_FILE_DISK_FULL
case 16: // NS_ERROR_FILE_NO_DEVICE_SPACE
strName = "diskFull";
break;
case 17: // NS_ERROR_FILE_NAME_TOO_LONG
strName = "fileNameTooLongError";
break;
case 19: // NS_ERROR_FILE_READ_ONLY
strName = "readOnly";
break;
case 21: // NS_ERROR_FILE_ACCESS_DENIED
strName = "accessError";
break;
}
const kBundle = "chrome://global/locale/nsWebBrowserPersist.properties";
var strBundle = Components.classes[this.mPearlUtil.kStringBundleCID]
.getService(this.mPearlUtil.kStringBundleInterface)
.createBundle(kBundle);
var s = strBundle.formatStringFromName(strName, [fileLoc.leafName], 1);
this.mPearlUtil.Alert(window, s);
}
},
endOfObject: true
};
window.addEventListener("load", function() { gAviaryMain.onLoad(); }, false);
// Pass null for aImageElement to capture an image of the active web page.
// aPagePortion and aRegionRect affect active page captures.
function AviaryCapturePageImage(aWindow, aImageElement,
aPagePortion, aRegionRect)
{
this.init(aWindow, aImageElement, aPagePortion, aRegionRect);
}
AviaryCapturePageImage.prototype =
{
mPearlUtil: null,
mWindow: null, // HTML Window
mCanvasContainer: null,
mCanvas: null,
mImageElement: null, // This remains null if capturing an entire web page.
mPagePortion: 0, // gAviaryMain.kPortionRegion, Visible, Entire.
mRegionRect: null, // Rectangular region to capture, if any.
mSourceW: 0, // Width of source page or image element.
mSourceH: 0, // Height of source page or image element.
mSourceXOffset: 0, // Horizontal offset within source page.
mSourceYOffset: 0, // Vertical offset within source page.
init: function(aWindow, aImageElement, aPagePortion, aRegionRect)
{
if (!aWindow)
this.onError("no window passed to Init"); // TODO: L10n
var isRegionCapture = (gAviaryMain.kPortionRegion == aPagePortion);
if ((isRegionCapture && !aRegionRect)
|| (!isRegionCapture && gAviaryMain.kPortionVisible != aPagePortion
&& gAviaryMain.kPortionEntire != aPagePortion))
{
this.onError("invalid page portion parameter"); // TODO: L10n
}
this.mPearlUtil = com.aviary.talon.pearlutil;
this.mWindow = aWindow;
this.mImageElement = aImageElement;
this.mPagePortion = aPagePortion;
if (isRegionCapture)
this.mRegionRect = aRegionRect;
var tbElem = document.getElementById("nav-bar");
if (!tbElem)
this.onError("did not find Navigation toolbar"); // TODO: L10n
const kXULNameSpace = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
const kHTMLNameSpace = "http://www.w3.org/1999/xhtml";
var sbElem = document.createElementNS(kXULNameSpace, "scrollbox");
sbElem.setAttribute("width", 1);
sbElem.setAttribute("height", 1);
var canvasElem = document.createElementNS(kHTMLNameSpace, "canvas");
canvasElem.setAttribute("style", "display:none");
sbElem.appendChild(canvasElem);
tbElem.appendChild(sbElem);
this.mCanvasContainer = sbElem;
this.mCanvas = canvasElem;
},
Cleanup: function()
{
this.mWindow = null;
this.mImageElement = null;
if (this.mCanvasContainer)
{
this.mCanvasContainer.parentNode.removeChild(this.mCanvasContainer);
this.mCanvasContainer= null;
}
},
DrawImageOnCanvas: function(aSizeObj)
{
try
{
var context = this.prepareCanvas();
if (aSizeObj && this.mCanvas)
{
aSizeObj.width = this.mCanvas.width;
aSizeObj.height = this.mCanvas.height;
}
if (this.mImageElement)
{
context.drawImage(this.mImageElement, 0, 0,
this.mSourceW, this.mSourceH);
}
else
{
var bgColor = "rgb(255,255,255)";
if (!this.mPearlUtil.GetBoolPref("browser.display.use_system_colors",
false))
{
bgColor = this.mPearlUtil.GetLocalizedStrPref(
"browser.display.background_color", bgColor);
}
context.drawWindow(this.mWindow,
this.mSourceXOffset, this.mSourceYOffset,
this.mSourceW, this.mSourceH, bgColor);
}
context.restore();
}
catch (e)
{
this.onError("unable to capture image"); // TODO: L10n
}
},
GetPNGDataURI: function()
{
if (!this.mCanvas)
return null;
return this.mCanvas.toDataURL("image/png");
},
// TODO: pass param with error? Components.results.NS_ERROR_INVALID_ARG
onError: function(aErrorMsg)
{
throw new Components.Exception(aErrorMsg,
Components.results.NS_ERROR_FAILURE);
},
// May throw. Returns a 2d drawing context.
// Callers should call context.restore() when done using the canvas.
// This function also sets this.mSourceXOffset, this.mSourceYOffset,
// this.mSourceW, and this.mSourceH.
prepareCanvas: function()
{
this.mCanvas.style.display = "inline"; // temporarily show the canvas.
var zoomFactor = 1.0;
this.mSourceW = 0;
this.mSourceH = 0;
this.mSourceXOffset = 0;
this.mSourceYOffset = 0;
if (this.mImageElement)
{
this.mSourceW = this.mImageElement.width;
this.mSourceH = this.mImageElement.height;
}
else if (this.mRegionRect)
{
this.mSourceW = this.mRegionRect.pageW;
this.mSourceH = this.mRegionRect.pageH;
this.mSourceXOffset = this.mRegionRect.startX;
this.mSourceYOffset = this.mRegionRect.startY;
}
else
{
var isEntirePage = (gAviaryMain.kPortionEntire == this.mPagePortion);
this.mSourceW = this.mPearlUtil
.GetWindowWidth(this.mWindow, isEntirePage);
this.mSourceH = this.mPearlUtil
.GetWindowHeight(this.mWindow, isEntirePage);
if (!isEntirePage)
{
this.mSourceXOffset = this.mWindow.pageXOffset;
this.mSourceYOffset = this.mWindow.pageYOffset;
}
}
// dump("sourceW: " + this.mSourceW + "; this.mSourceH: " + this.mSourceH + "\n");
var canvasW = this.mSourceW * zoomFactor;
var canvasH = this.mSourceH * zoomFactor;
this.mCanvas.style.width = canvasW + "px";
this.mCanvas.style.height = canvasH + "px";
this.mCanvas.style.maxWidth = canvasW + "px";
this.mCanvas.style.maxHeight = canvasH + "px";
this.mCanvas.width = canvasW;
this.mCanvas.height = canvasH;
var context = this.mCanvas.getContext("2d");
context.clearRect(0, 0, canvasW, canvasH);
context.save();
context.scale(zoomFactor, zoomFactor);
return context;
},
endOfObject: true
};